package com.idol.config;

import com.idol.io.Resource;
import com.idol.pojo.Configeration;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * 数据库配置文件解析类
 *
 * @author Supreme_Sir
 * @version 1.0
 * @className XMLConfigBuilder
 * @description
 * @date 2020/9/26 15:22
 **/
public class XMLConfigBuilder {
    private Configeration configeration;

    public XMLConfigBuilder() {
        this.configeration = new Configeration();
    }

    /**
     * 该方法用于将 xml 解析成配置文件对象
     * @param inputStream sqlMapConfig.xml 配置文件的 InputStream 对象
     * @return
     */
    public Configeration parseConfig(InputStream inputStream) throws DocumentException, PropertyVetoException {
        // 解析 sqlMapConfig.xml
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();
        List<Element> propertyList = rootElement.selectNodes("//property");
        Properties dataSourceProperties = new Properties();
        for (Element element : propertyList) {
            String name = element.attributeValue("name");
            String value = element.attributeValue("value");
            dataSourceProperties.put(name, value);
        }

        // 创建 c3p0 数据库连接池
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        comboPooledDataSource.setDriverClass(dataSourceProperties.getProperty("driverClass"));
        comboPooledDataSource.setJdbcUrl(dataSourceProperties.getProperty("jdbcUrl"));
        comboPooledDataSource.setUser(dataSourceProperties.getProperty("user"));
        comboPooledDataSource.setPassword(dataSourceProperties.getProperty("password"));
        this.configeration.setDataSource(comboPooledDataSource);

        // 解析 Mapper.xml
        List<Element> mapperList = rootElement.selectNodes("//mapper");
        for (Element element : mapperList) {
            String mapperPath = element.attributeValue("resource");
            InputStream mapperStream = Resource.getResourceAsStream(mapperPath);
            XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(this.configeration);
            xmlMapperBuilder.parse(mapperStream);
        }

        return this.configeration;
    }
}
